#!/bin/bash
# Version: 2.3.2
# Publisher: argor

CURRENT_DIR=`dirname $0`
#echo "Get current-dir: " $CURRENT_DIR
AppName=`ls -1 $CURRENT_DIR | grep "\.jar$"`
#echo "Component AppName: " $AppName
LOGFILE=${CURRENT_DIR}/$(echo $AppName | sed 's/\.jar/\.log/')

if [ -z $1 ]; then
    echo "Parameter error when calling."
    exit 1
else if [ "$(id -u)" -ne 0 ]; then
    echo "You must be root."
    exit 2
else
    echo ""
    #echo "Component Executing: " $0 $@
fi
fi

# Script execution environment.
# Default: Deve
# Optional value: Deve, Prod
# The test environment is running, and only the jar package is started and the log is written.
# In the production environment, custom JVM parameters and startup parameters are also used.
EXEC_ENV="Deve"
# Custom JVM parameters
JVM_OPTS=" -Dspring.profiles.active=uat -Duser.timezone=Asia/Shanghai -Xms512M -Xmx512M -XX:PermSize=256M -XX:MaxPermSize=512M -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC "
LIST_PORT="7003"
# Startup parameters
SERVER_OPTS=" --server.port=${LIST_PORT} "

############################ son function ###############################
function checkJar() {
    if [ -z $AppName ]; then
        echo -e "\033[0;31m \tCan't find jar to running. \033[0m"
        exit 1
    fi
}

# Get pid of some java process that name is $AppName.
function getPid() {
    ps -C java -o pid,cmd | grep $AppName | grep -v "grep --color=auto"| awk '{print $1}'
}

# Get listen port by parameter $1.
function getPorts() {
    netstat -nlp | grep $1 | awk '{print $4}'
}
############################ son function ###############################

#-----------------------------------------------------------------------#

############################ main function ###############################
function start() {
    checkJar || echo $?
    echo `date` " Try start: " $AppName > $LOGFILE
    echo -e "  \033[34m \bTry start app: " $AppName "\b\033[0m"
    #PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
    PID=`getPid`
    if [ x"$PID" != x"" ]; then
        echo -e "\033[0;31m \t$AppName is running. \033[0m" "pid: " $PID
    else
        local -i cancelUntil=0
        until [ x"$PID" != x"" ];do
	    #echo -e "\tcancelUntil: $cancelUntil"
	    if [ $cancelUntil -ge 3 ]; then
	        break
	    else
	        let cancelUntil+=1
	    fi

            if [ $cancelUntil -eq 1 ]; then
                echo -e "\tAppName " ${CURRENT_DIR}/$AppName " will be starting..."
	    else
	        echo -e "\t  ...try again..."
	    fi
	    # Check start options.
	    #echo -------------$JVM_OPTS
	    #echo -------------${CURRENT_DIR}/${AppName}
	    #echo -------------${SERVER_OPTS} 
	    # Check start envirment.
	    if [ $EXEC_ENV == "Prod" ]; then
                nohup java -jar $JVM_OPTS ${CURRENT_DIR}/${AppName} ${SERVER_OPTS} &>> $LOGFILE &
	    else if [ $EXEC_ENV == "Deve" ]; then
                nohup java -jar $JVM_OPTS ${CURRENT_DIR}/${AppName} &>> $LOGFILE &
	    else
	        echo -e "\t \033[44;37m \b\bInvalid EXEC_ENV\033[0m"
		exit 3
	    fi;fi
	    # when first-start fialure will logging.
	    if [ $cancelUntil -gt 0 ]; then
                echo `date` " AppName " ${CURRENT_DIR}/$AppName " will be starting...<try:${cancelUntil}>" >> $LOGFILE
	    fi

            sleep 2
            PID=`getPid`
	done

	if [ $cancelUntil -ge 3 ]; then
	    echo -e "\t尝试3次启动均以失败，放弃启动"
	else
	    #echo -e "\t${AppName}'s pid: ${PID}"
	    # Check app's start command.
	    #ps -p $PID -o pid,user,cmd
            echo -e "\t \033[0;31m \b\bStart $AppName success. \033[33m pid: "$PID"\033[0m"
	fi
    fi  
}

function stop() {
    checkJar || echo $?
    echo `date` " Try stop app: " $AppName >> $LOGFILE
    echo -e "   \033[0;34m \b\bTry stop $AppName \033[0m"
    
        PID=""
        query(){
                PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
        }   

        query
        if [ x"$PID" != x"" ]; then
                kill -TERM $PID
                echo -e "\t$AppName \033[33m \bpid:$PID\033[0m exiting..."
                while [ x"$PID" != x"" ]
                do
                        sleep 2
                        query
                done
                echo -e "\t \033[0;31m \b\b$AppName exited. \033[0m"
        else
                echo -e "\t$AppName already stopped."
        fi  
}

function status() {
    checkJar || echo $?
    PID=`getPid`

    if [ "x"${PID}"y" != "xy" ];then
        echo -e "\t \033[0;31m \b\b$AppName is running. \033[33m" "pid: ${PID}\033[0m" 
        local -a ports
        ports=`getPorts $PID`
	echo -e "\t  Listen:"
	for p in $ports; do
	    echo -e "\t    $p"
	done
    else
        echo -e "\t$AppName was stoped or not running at all."
    fi
}
############################ main function ###############################

case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        stop
        sleep 2
        start
        ;;
esac
